package com.lfz.quality_effect.service.impl;

import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.generator.config.IFileCreate;
import com.lfz.quality_effect.constant.LfzConstant;
import com.lfz.quality_effect.model.Test;
import com.lfz.quality_effect.model.entity.TIndexItem;
import com.lfz.quality_effect.model.entity.TIndexScore;
import com.lfz.quality_effect.mapper.TIndexScoreMapper;
import com.lfz.quality_effect.model.vo.*;
import com.lfz.quality_effect.service.TIndexItemService;
import com.lfz.quality_effect.service.TIndexScoreService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lfz.quality_effect.utils.ExcelListener;
import com.lfz.quality_effect.utils.LogUtils;
import com.lfz.quality_effect.utils.ResultData;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 指标得分表 服务实现类
 * </p>
 *
 * @author Destiny
 * @since 2023-03-03
 */
@Service
public class TIndexScoreServiceImpl extends ServiceImpl<TIndexScoreMapper, TIndexScore> implements TIndexScoreService {


    @Autowired
    private TIndexItemService indexItemService;
    @Override
    public void uploadIndexItemScore(MultipartFile file,String court,String dataTime) {
        ExcelListener listener = new ExcelListener();
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //传入参数
        ExcelReader excelReader = new ExcelReader(inputStream, null, listener);
        //读取信息
        excelReader.read(new Sheet(1, 1, Test.class));
        List<Object> objectList =listener.getDatas();
        //得分项
        List<TIndexScore> indexScoreList = new ArrayList<>();



        for (int i=0;i<objectList.size();i++){
            Test mediateCaseDTO = (Test)objectList.get(i);
            //LogUtils.write(JSON.toJSONString(mediateCaseDTO)+"法院：===="+court);
            //先查询是否存在，存在修改。不存在在新增
            TIndexScore indexScore =  this.getOne(new LambdaQueryWrapper<TIndexScore>()
                    .eq(TIndexScore::getIndexId,mediateCaseDTO.getIndexId())
                    .eq(TIndexScore::getCourt,court)
                    .eq(TIndexScore::getDataTime,dataTime));
            if (indexScore == null){
                indexScore = new TIndexScore();
                indexScore.setCreateTime(LocalDateTime.now());
            }
            BeanUtils.copyProperties(mediateCaseDTO,indexScore);
            indexScore.setDataTime(dataTime);
            indexScore.setCourt(court);
            indexScoreList.add(indexScore);
        }
        this.saveOrUpdateBatch(indexScoreList);
        //  indexItemService.saveBatch(indexItemList);
    }

    @Override
    public List<ScoreRankVO> getScoreRank() {
        List<String> list = new ArrayList<>();
        list.add("乐平法院");
        list.add("昌江法院");
        list.add("浮梁法院");
        list.add("珠山法院");
        List<ScoreRankVO> lastScoreList = new ArrayList<>();
        List<ScoreRankVO> scoreRankVOList =  this.getBaseMapper().getScoreRank(list);
        for (int i=0;i<scoreRankVOList.size();i++){
            ScoreRankVO scoreRankVO = scoreRankVOList.get(i);

            if (i !=0 && scoreRankVO.getScore().compareTo(scoreRankVOList.get(i-1).getScore())==0){
                scoreRankVO.setSort(scoreRankVOList.get(i-1).getSort());
            }else {
                scoreRankVO.setSort(i+1);

            }
            String court = scoreRankVO.getCourt();
            if (court.contains(LfzConstant.ZHUSHAN_COURT) || court.contains(LfzConstant.FULIANG_COURT)
                    || court.contains(LfzConstant.LEPU_COURT) || court.contains(LfzConstant.CHANGJIANG_COURT)
                    || i==0){
                lastScoreList.add(scoreRankVO);
            }
        }

        //标杆法院
//        //ScoreRankVO scoreRankVO =   scoreRankVOList.get(0);
//
//        scoreRankVOList =  scoreRankVOList.stream().filter(item->item.getCourt().contains(LfzConstant.LEPU_COURT) || item.getCourt().contains(LfzConstant.CHANGJIANG_COURT)|| item.getCourt().contains(LfzConstant.FULIANG_COURT) || item.getCourt().contains(LfzConstant.ZHUSHAN_COURT)).collect(Collectors.toList());
//        scoreRankVOList.add(scoreRankVO);
        return lastScoreList;
    }

    @Override
    public NonPerfectIndexVO getNonPerfectScoreInfo() {

        NonPerfectIndexVO nonPerfectIndexVO = new NonPerfectIndexVO();
        List<LepingNonPerfectVO> lepingNonPerfectVOList = this.getBaseMapper().getNonPerfectScoreInfo();
        //全部都是满分
        if (CollectionUtils.isEmpty(lepingNonPerfectVOList)){
            return null;
        }

        //浮梁指标得分集合
        List<FuliangNonPerfectVO> fuliangNonPerfectVOList  = new ArrayList<>();
        //昌江指标得分集合

        List<ChangjiangNonPerfectVO> changjiangNonPerfectVOList = new ArrayList<>();
        //珠山指标得分集合
        List<ZhushanNonPerfectVO> zhushanNonPerfectVOList = new ArrayList<>();

        //过滤出非满分项的id
        List<String> strings = lepingNonPerfectVOList.stream().map(item->item.getIndexId()).collect(Collectors.toList());

        //查询比较法院的所有得分
        List<IndexScoreVO> indexScoreVOList =   this.getBaseMapper().getBatchNonPerfectScore(strings, LfzConstant.getInitCourtList());
        for (IndexScoreVO indexScoreVO:indexScoreVOList){
            String court = indexScoreVO.getCourt();
            if (court.contains(LfzConstant.ZHUSHAN_COURT)){
                ZhushanNonPerfectVO zhushanNonPerfectVO = new ZhushanNonPerfectVO();
                BeanUtils.copyProperties(indexScoreVO,zhushanNonPerfectVO);
                zhushanNonPerfectVOList.add(zhushanNonPerfectVO);
            }
            if (court.contains(LfzConstant.CHANGJIANG_COURT)){
                ChangjiangNonPerfectVO changjiangNonPerfectVO = new ChangjiangNonPerfectVO();
                BeanUtils.copyProperties(indexScoreVO,changjiangNonPerfectVO);
                changjiangNonPerfectVOList.add(changjiangNonPerfectVO);
            }
            if (court.contains(LfzConstant.FULIANG_COURT)){
                FuliangNonPerfectVO fuliangNonPerfectVO = new FuliangNonPerfectVO();
                BeanUtils.copyProperties(indexScoreVO,fuliangNonPerfectVO);
                fuliangNonPerfectVOList.add(fuliangNonPerfectVO);
            }
        }
        nonPerfectIndexVO.setChangjiangNonPerfectVOList(changjiangNonPerfectVOList);
        nonPerfectIndexVO.setZhushanNonPerfectVOList(zhushanNonPerfectVOList);
        nonPerfectIndexVO.setFuliangNonPerfectVOList(fuliangNonPerfectVOList);
        nonPerfectIndexVO.setLepingNonPerfectVOList(lepingNonPerfectVOList);

        //查询非满分项的标杆法院对应分数
        List<PolePerfectVO> polePerfectVOList = this.getBaseMapper().getPolePerfectList(strings);
        Map<String,List<PolePerfectVO>> stringListMap = polePerfectVOList.stream().collect(Collectors.groupingBy(item->item.getIndexId()));

        Map<String,PolePerfectVO> map = new HashMap<>();
        stringListMap.keySet().forEach(item->{
            PolePerfectVO polePerfectVO =  stringListMap.get(item).stream().max(Comparator.comparing(PolePerfectVO::getIndexAddScore)).get();
            map.putIfAbsent(item,polePerfectVO);

        });

        Map<String, PolePerfectVO> configMap = polePerfectVOList.parallelStream().collect(Collectors.groupingBy(PolePerfectVO::getIndexId, // 先根据appId分组
                Collectors.collectingAndThen(Collectors.reducing(( c1,  c2) -> c1.getIndexAddScore().compareTo(c2.getIndexAddScore()) ==1 ? c1 : c2), Optional::get)));

        List<PolePerfectVO> lastPoleList = new ArrayList<>();
        for (Map.Entry<String,PolePerfectVO> entry:configMap.entrySet()){
            lastPoleList.add(entry.getValue());
        }
        // map.values().stream().sorted(Comparator.comparing(PolePerfectVO::getIndexAddScore));
        nonPerfectIndexVO.setPolePerfectVOList(lastPoleList);

        return nonPerfectIndexVO;
    }




    /**
     * 获取速裁快审
     * @return
     */
    @Override
    public ResultData getJudgeQuicklyScoreInfo(String name) {
        List<ScoreRankVO> indexScoreVOList =  this.getBaseMapper().getJudgeQuicklyScoreInfo(name);
        if (CollectionUtils.isEmpty(indexScoreVOList)){
            return null;
        }
        List<ScoreRankVO> lastScoreList = new ArrayList<>();

        //  for (ScoreRankVO scoreRankVO:indexScoreVOList){
        for (int i=0;i<indexScoreVOList.size();i++){
            ScoreRankVO scoreRankVO = indexScoreVOList.get(i);
            String court = scoreRankVO.getCourt();

            if (i!=0&& scoreRankVO.getScore().compareTo(indexScoreVOList.get(i-1).getScore())==0){
                scoreRankVO.setSort(indexScoreVOList.get(i-1).getSort());
            }else {
                scoreRankVO.setSort(i+1);

            }
            if (court.contains(LfzConstant.CHANGJIANG_COURT) || court.contains(LfzConstant.ZHUSHAN_COURT)
                    || court.contains(LfzConstant.FULIANG_COURT) || court.contains(LfzConstant.LEPU_COURT)){
                lastScoreList.add(scoreRankVO);
            }
        }
        ScoreRankVO scoreRankVO = indexScoreVOList.get(0);
        lastScoreList.add(scoreRankVO);
        return ResultData.ok().data(lastScoreList);
    }

    /**
     * 获取电子送达率得分排名信息
     * @param name
     * @return
     */
    @Override
    public ResultData getElectronicDeliveryScoreInfo(String name) {
        List<ScoreRankVO> indexScoreVOList =  this.getBaseMapper().getElectronicDeliveryScoreInfo(name);
        if (CollectionUtils.isEmpty(indexScoreVOList)){
            return null;
        }
        List<ScoreRankVO> lastScoreList = new ArrayList<>();
        //for (ScoreRankVO scoreRankVO:indexScoreVOList){
        for (int i=0;i<indexScoreVOList.size();i++){
            ScoreRankVO scoreRankVO = indexScoreVOList.get(i);
            String court = scoreRankVO.getCourt();
            if (i!=0 && scoreRankVO.getScore().compareTo(indexScoreVOList.get(i-1).getScore()) == 0){
                scoreRankVO.setSort(indexScoreVOList.get(i-1).getSort());
            }else {
                scoreRankVO.setSort(i+1);
            }
            if (court.contains(LfzConstant.CHANGJIANG_COURT) || court.contains(LfzConstant.ZHUSHAN_COURT)
                    || court.contains(LfzConstant.FULIANG_COURT) || court.contains(LfzConstant.LEPU_COURT)){
                lastScoreList.add(scoreRankVO);
            }
        }
        ScoreRankVO scoreRankVO = indexScoreVOList.get(0);
        lastScoreList.add(scoreRankVO);
        return ResultData.ok().data(lastScoreList);
    }

    /**
     * 获取指定法院的预警信息
     * @param court
     */
    @Override
    public List<EarnWarnVO> getEarnWarningInfo(String court) {
        List<TIndexItem> indexItemList = indexItemService.list(new LambdaQueryWrapper<TIndexItem>()
                .eq(TIndexItem::getType,LfzConstant.LFZ_ONE));
        if (CollectionUtils.isEmpty(indexItemList)){
            return null;
        }
        List<String> nameList =  indexItemList.stream().map(item->item.getIndexName()).collect(Collectors.toList());
        List<EarnWarnVO> earnWarnVOList = this.getBaseMapper().getEarnWarningInfo(nameList,court);

        for (EarnWarnVO earnWarnVO:earnWarnVOList){
            String indexValue= earnWarnVO.getIndexValue();
            String marign =  LfzConstant.getMargin(earnWarnVO.getIndexName(),indexValue,earnWarnVO.getScoreCriteria());
            earnWarnVO.setMargin(marign);
        }
        return earnWarnVOList;
    }

    @Override
    public  Map<String, List<EleScoreRankVO>> electronicDeliveryTrand(String name,String startTime, String endTime) {
        //先查近期内所有法院的
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("startTime",startTime);
        paramMap.put("endTime",endTime);
        paramMap.put("indexName",name);
        List<String> list=  LfzConstant.getInitCourtList();

        List<EleScoreRankVO> eList = new ArrayList<>();

        List<EleScoreRankVO> standartCourtList = this.getBaseMapper().getStandardCourt(paramMap);


        Map<String, List<EleScoreRankVO>> eMap =  standartCourtList.stream().sorted(Comparator.comparing(EleScoreRankVO::getScore).reversed()).collect(Collectors.groupingBy(item->item.getDataTime()));

        for (Map.Entry<String,List<EleScoreRankVO>> entry:eMap.entrySet()){
            eList.add(entry.getValue().get(0));
        }


        List<EleScoreRankVO> eleScoreRankVOList = this.getBaseMapper().getAllElectronDeliveryTrend(paramMap);
      //  Map<String,List<EleScoreRankVO>> eMap =   eleScoreRankVOList.stream().sorted(Comparator.comparing(EleScoreRankVO::getScore).reversed()).collect(Collectors.groupingBy(item->item.getDataTime()));

//        for (Map.Entry<String,List<EleScoreRankVO>> entry: eMap.entrySet()){
//            List<EleScoreRankVO> eValue = entry.getValue();
//            for (int i=0;i<eValue.size();i++){
//                EleScoreRankVO eleScoreRankVO = eValue.get(i);
//                if (i !=0 && eleScoreRankVO.getScore().compareTo(eValue.get(i-1).getScore())==0){
//                    eleScoreRankVO.setSort(eValue.get(i-1).getSort());
//                }else {
//                    eleScoreRankVO.setSort(i+1);
//                }
//            }
//        }

        Map<String, List<EleScoreRankVO>> groupMap =  eleScoreRankVOList.stream().sorted(Comparator.comparing(EleScoreRankVO::getScore).reversed()).collect(Collectors.groupingBy(item->item.getCourt()));

        Map<String,List<EleScoreRankVO>> map = new HashMap<>();

        for (Map.Entry<String,List<EleScoreRankVO>> entry:groupMap.entrySet()){

            String key =  entry.getKey();

            if (key.contains(LfzConstant.CHANGJIANG_COURT) || key.contains(LfzConstant.ZHUSHAN_COURT)
                    || key.contains(LfzConstant.FULIANG_COURT) || key.contains(LfzConstant.LEPU_COURT)){
                map.put(entry.getKey(),entry.getValue());
            }
        }
        map.put("标杆法院",eList);
        return map;
    }

    @Override
    public Map<String, List<EleScoreRankVO>> quicklyJudgeTrend(String name, String startTime, String endTime) {
        //先查近期内所有法院的
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("startTime",startTime);
        paramMap.put("endTime",endTime);
        paramMap.put("indexName",name);
        List<String> list=  LfzConstant.getInitCourtList();

        List<EleScoreRankVO> eList = new ArrayList<>();


        //查出所有的法院
        List<EleScoreRankVO> standartCourtList = this.getBaseMapper().getStandardCourtByJudge(paramMap);

        //按照时间分组，排序
        Map<String, List<EleScoreRankVO>> eMap =  standartCourtList.stream().sorted(Comparator.comparing(EleScoreRankVO::getScore)).collect(Collectors.groupingBy(item->item.getDataTime()));

        for (Map.Entry<String,List<EleScoreRankVO>> entry:eMap.entrySet()){
            eList.add(entry.getValue().get(0));
        }



        List<EleScoreRankVO> eleScoreRankVOList = this.getBaseMapper().getAllElectronDeliveryTrend(paramMap);
        //按照法院分组
        Map<String, List<EleScoreRankVO>> groupMap =  eleScoreRankVOList.stream().sorted(Comparator.comparing(EleScoreRankVO::getScore)).collect(Collectors.groupingBy(item->item.getCourt()));

        Map<String,List<EleScoreRankVO>> map = new HashMap<>();

        for (Map.Entry<String,List<EleScoreRankVO>> entry:groupMap.entrySet()){
            String key = entry.getKey();
            // List<EleScoreRankVO> eleScoreRankVOList1 =  entry.getValue().sort(Comparator.comparing(EleScoreRankVO::getScore));
//            List<EleScoreRankVO> eleScoreRankVOS = entry.getValue();
//            List<EleScoreRankVO> lastScoreList = new ArrayList<>();
//            for (int i=0;i<eleScoreRankVOS.size();i++){
//                EleScoreRankVO eleScoreRankVO = eleScoreRankVOS.get(i);
//                String court = eleScoreRankVO.getCourt();
//                if (i !=0 && eleScoreRankVO.getScore().compareTo(eleScoreRankVOS.get(i-1).getScore()) ==0){
//                    eleScoreRankVO.setSort(eleScoreRankVOS.get(i-1).getSort());
//                }else {
//                    eleScoreRankVO.setSort(i+1);
//                }
//                if (court.contains(LfzConstant.CHANGJIANG_COURT) || court.contains(LfzConstant.ZHUSHAN_COURT)
//                        || court.contains(LfzConstant.FULIANG_COURT) || court.contains(LfzConstant.LEPU_COURT)){
//                    lastScoreList.add(eleScoreRankVO);
//                }
//            }
//            lastScoreList.add(eleScoreRankVOS.get(0));

            if (key.contains(LfzConstant.CHANGJIANG_COURT) || key.contains(LfzConstant.ZHUSHAN_COURT)
                    || key.contains(LfzConstant.FULIANG_COURT) || key.contains(LfzConstant.LEPU_COURT)){
                map.put(entry.getKey(),entry.getValue());
            }
           // map.put(entry.getKey(),entry.getValue());
        }
        map.put("标杆法院",eList);
        return map;
    }
}
